import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86156
 * Date: 2022-03-08
 * Time: 15:41
 */
public class MyArrayList {
    int[] elem;
    int usedSize;

    //create an arraylist
    public void setArray() {
        this.elem = new int[10];
        this.usedSize = 0;
    }

    //print the arraylist
    public void display() {
        for (int i = 0 ; i < this.usedSize; i++) {
            System.out.print(this.elem[i] + " ");
        }
        System.out.println();
    }

    public int listLength() {
        return this.usedSize;
    }
    //add an element to the given position
    public void addElement(int pos, int data) {
        if (pos < 0 || pos > usedSize) {
            System.out.println("pos 位置不合法!");
        } else {
            if (isFull())
            {
                this.elem = Arrays.copyOf(this.elem, 2 * this.elem.length);
            }
            for (int i = usedSize - 1; i >= pos; i--) {
                this.elem[i + 1] = this.elem[i];
            }
            this.elem[pos] = data;
            this.usedSize++;
        }
    }

    //check the arraylist is full
    public boolean isFull() {
            return this.usedSize == this.elem.length;
    }

    //check if there is the given element in the arraylist
    public int checkElement(int toFind)
    {
        if (isNone()) {
            System.out.println("列表为空!");
        } else {
            for (int i = 0; i < this.usedSize; i++) {
                if (this.elem[i] == toFind) {
                    return i;
                }
            }
        }
        return -1;
    }

    //search the element at the given position
    public int getElement(int pos) {
        if (isNone()) {
            System.out.println("列表为空!");
            return -1;
        }
        if (pos < 0 || pos >= usedSize) {
            System.out.println("pos 位置不合法!");
            return -1;
        }
        return this.elem[pos];
    }

    //check the arraylist is empty
    public boolean isNone() {
        return this.usedSize == 0;
    }

    //remove the given data from the arraylist
    public void removeElement(int data)
    {
        int pos = checkElement(data);
        if (pos == -1) {
            System.out.println("表中不存在该数据!");
        } else {
            for (int i = pos; i < usedSize - 1; i++) {
                this.elem[i] = this.elem[i + 1];
            }
            this.usedSize--;
        }
    }

    //remove the element at the given position
    public void removePosition(int pos) {
        if (isNone()) {
            System.out.println("列表为空!");
        } else if (pos < 0 || pos >= usedSize) {
            System.out.println("pos 位置不合法!");
        } else {
        for (int i = pos; i < usedSize - 1; i++) {
                this.elem[i] = this.elem[i + 1];
            }
            this.usedSize--;
        }
    }

    public void clear() {
        this.usedSize = 0;
    }
}
